//
//  WCNWoundDetailVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/18.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNWoundDetailVC.h"
#import "WCNFirstBodyPartVC.h"
#import "WCNMulTextEditVC.h"
//
#import "WCPickerView.h"
#import "WCButton.h"
#import "WCNMulTextTCell.h"
//
#import "NSString+Utilities.h"
#import "UILabel+Utilities.h"
#import "UINavigationItem+Offset.h"
//
#import "Patient.h"
#import "WCDefaultManager.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
//
#import "Macros.h"
#import "Constants.h"
#import "WSJWoundDesVC.h"
#import "JCAlertView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "WCNWoundDesCell.h"
#import "WCInfoEditView.h"
#import "UMMobClick/MobClick.h"


static NSString *cellId = @"WCNMulTextTCell";

@interface WCNWoundDetailVC ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;

@property (nonatomic) WCNWoundDetailVCMode mode;
@property (strong, nonatomic) NSMutableDictionary *data;
@property (nonatomic,  strong) UIButton *saveBtn;
@end

@implementation WCNWoundDetailVC

- (instancetype)initWith:(NSDictionary *)data mode:(WCNWoundDetailVCMode)mode
{
    self = [super init];
    if (self) {
        if (mode == WCNWoundDetailVCModeAdd) {
            self.title = @"新增伤口";
            _data = [NSMutableDictionary dictionary];
            //_data = [NSMutableDictionary dictionaryWithDictionary:data];
        } else if (mode == WCNWoundDetailVCModeScan) {
            self.title = @"伤口详情";
            
            _data = [NSMutableDictionary dictionaryWithDictionary:data];
        }else if (mode == WCNWoundDetailVCModeEdit) {
            self.title = @"编辑伤口";
            _data = [NSMutableDictionary dictionaryWithDictionary:data];
        }

        _mode = mode;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (self.mode == WCNWoundDetailVCModeAdd | self.mode == WCNWoundDetailVCModeEdit) {
        WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
        [rightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
        _saveBtn = rightBtn;
        [self.navigationItem addRightBarButtonItem:rightBtn];
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil]  forCellReuseIdentifier:cellId];
    [self.tableView registerNib:[UINib nibWithNibName:@"WCNWoundDesCell" bundle:nil] forCellReuseIdentifier:@"WCNWoundDesCell"];
    /*
    self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:cellId];
    //加上宽度约束后，动态计算高度才有效
    [self.prototypeCell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.prototypeCell.contentView
                                                                               attribute:NSLayoutAttributeWidth
                                                                               relatedBy:NSLayoutRelationEqual
                                                                                  toItem:nil
                                                                               attribute:NSLayoutAttributeNotAnAttribute
                                                                              multiplier:1
                                                                                constant:kScreenWidth]];
    self.prototypeCell.mulText.numberOfLines = 0;
     */
}
- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = kAppBg;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview: _tableView];
    }
    return  _tableView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
}

- (void)pageBack{
    if (self.mode == WCNWoundDetailVCModeScan) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
    
        defineWeakSelf;
        [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"是否放弃编辑" ButtonType:0 ButtonTitle:@"放弃编辑" Click:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } ButtonType:1 ButtonTitle:@"继续编辑" Click:^{
            
        }];
    }
}


- (void)inputDesc {
    if (_mode == WCNWoundDetailVCModeAdd | _mode == WCNWoundDetailVCModeEdit) {

        defineWeakSelf;
        WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
        vc.title = @"伤口描述";
        vc.textViewPlaceholder = @"请填写伤口描述";
        vc.textViewValue = self.data[@"description"];
        vc.canEmpty = YES;
        vc.callback = ^(NSString *text){
            weakSelf.data[@"description"] = text;
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)addWoundDesc {
    if (_mode == WCNWoundDetailVCModeAdd | _mode == WCNWoundDetailVCModeEdit) {
        
        defineWeakSelf;
        WSJWoundDesVC *vc =[WSJWoundDesVC new];
        vc.callBackStr = ^(NSString *str){
           // [weakSelf setDesc:str];
            weakSelf.data[@"description"] = str;
            [weakSelf.tableView reloadData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (void)save
{
    NSString *type = self.data[@"type"];
    if (!type || [type isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择伤口类型" withView:self.view];
        return;
    }
    NSString *bodyPartCode = self.data[@"bodyPartCode"];
    if (!bodyPartCode || [bodyPartCode isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择伤口部位" withView:self.view];
        return;
    }
    self.saveBtn.enabled = NO;
    Account *account = [[WCDefaultManager shareMg] account];
    NSString *url;
    NSDictionary *params;
    switch (self.mode) {
        case WCNWoundDetailVCModeAdd:{
            url = kAddWoundRecord;
            params = @{@"recordId": self.patient.stringId,
                       @"type": type,
                       @"bodyPartName": self.data[@"bodyPartName"],
                       @"bodyPartCode": self.data[@"bodyPartCode"],
                       @"description": self.data[@"description"]?self.data[@"description"]:@"",
                       @"createBy": account.stringId};

        }
            break;
        case WCNWoundDetailVCModeEdit:{
            url = kUpdateWoundRecordByRecordId;
             params = @{@"id":self.data[@"id"],
                        @"type": type,
                        @"bodyPartName": self.data[@"bodyPartName"],
                        @"bodyPartCode": self.data[@"bodyPartCode"],
                        @"description": self.data[@"description"]?self.data[@"description"]:@""};
        }
            break;
            
        default:
            break;
    }
   
    defineWeakSelf;
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
    [[WCNetworkAccessManager sharedMg] POST:url parameters:params success:^(NSDictionary *result){
        
        //统计增加伤口
        if (weakSelf.mode == WCNWoundDetailVCModeAdd) {
            [MobClick  event:AddWound];
        }else{ //统计修改伤口
         [MobClick  event:MotifyWound];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:CareRecordsRefreshNotification object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WoundRecordsRefreshNotification" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:PatientsRefreshNotification object:nil];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failure:nil netError:nil always:^{
        [hud hide:YES];
        _saveBtn.enabled = YES;
    }];
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>
// 设置sectionHeader的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        
        if (indexPath.row == 2) {
            WCNWoundDesCell *woundDesCell =[tableView dequeueReusableCellWithIdentifier:@"WCNWoundDesCell" forIndexPath:indexPath];
            woundDesCell.desLabel.text = self.data[@"description"];
            woundDesCell.modeClicked = ^{
                [self addWoundDesc];
            
            };
            return woundDesCell;
        }
        WCNMulTextTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.mulText.textAlignment = NSTextAlignmentRight;
        cell.mulText.numberOfLines = 1;
        
        switch (indexPath.row) {
            case 0: {
                cell.textTitle.text = @"伤口类型";
                cell.mulText.text = self.data[@"type"];
            }
                break;
            case 1: {
                cell.textTitle.text = @"伤口部位";
                cell.mulText.text = self.data[@"bodyPartName"];
            }
                break;
                
        }
        if (self.mode == WCNWoundDetailVCModeScan | self.mode == WCNWoundDetailVCModeEdit) {
            [cell.arowImg removeFromSuperview];
        }
        
        return cell;
        
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (self.mode == WCNWoundDetailVCModeEdit | self.mode == WCNWoundDetailVCModeAdd) {
        switch (indexPath.row) {
            case 0: {
                if (self.mode == WCNWoundDetailVCModeEdit) {
                    return;
                }
                NSArray *types = @[@"压疮", @"手术伤口", @"烫伤烧伤", @"皮肤撕裂", @"糖尿病溃疡", @"皮肤擦伤", @"静脉和动脉性溃疡", @"部分或全层移植", @"放射性皮炎", @"药物渗漏伤", @"留置针", @"其他"];
                NSString *type = self.data[@"woundType"];
                NSUInteger index = [types indexOfObject:type];
                if (index == NSNotFound) {
                    index = 0;
                }
                
                WCPickerView *picker = [[WCPickerView alloc] init];
                picker.titleLabel.text = @"伤口类型";
                picker.pickerDataSource = types;
                [picker.picker selectRow:index inComponent:0 animated:YES];
                picker.close = ^(NSInteger selected){
                    if (selected == types.count - 1) {
                        WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                        editView.titleLabel.text = @"伤口类型";
                        //editView.textField.keyboardType = UIKeyboardTypePhonePad;
                        editView.limitLenth = 20;
                        editView.save = ^(NSString *txt){
                            if (![txt isEmpty]) {
                                self.data[@"type"] = txt;
                                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                                return YES;
                            }
                            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                            return NO;
                        };
                        [editView showIn:self.navigationController.view animated:YES];
                    }else {
                    
                        self.data[@"type"] = types[selected];
                    }
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                };
                [picker show:self.navigationController completion:nil];
                break;
            }
            case 1: {
                if (self.mode == WCNWoundDetailVCModeEdit) {
                    return;
                }
                WCNFirstBodyPartVC *vc = [[WCNFirstBodyPartVC alloc] initWithPatient:self.patient];
                vc.wound = self.data;
                [self.navigationController pushViewController:vc animated:YES];
                break;
            }
            case 2: {
                WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
                vc.title = @"伤口描述";
                vc.textViewPlaceholder = @"请填写伤口描述";
                vc.textViewValue = self.data[@"description"];
                vc.canEmpty = YES;
                vc.callback = ^(NSString *text){
                    self.data[@"description"] = text;
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                };
                [self.navigationController pushViewController:vc animated:YES];
                break;
            }
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

        if (indexPath.row == 2) {
            CGFloat h = [tableView fd_heightForCellWithIdentifier:@"WCNWoundDesCell" configuration:^(WCNWoundDesCell *cell) {
                cell.desLabel.text = self.data[@"description"];;
            }];
            return MAX(kOnePX+h, 45.0);;
        }
        return 45;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return 3;
}


@end
